<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\game\Gamechild;
use app\common\model\game\Gameroom;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','wechatlogin_minapp'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();



        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    public function wechatlogin_minapp(){
        $platform = 'wechat';
        $code = $this->request->post("code");
        $nickname = $this->request->post("nickname");
        $avatar = $this->request->post("avatar");
        $pid = $this->request->post('parid',0);
        if($code == ''){
            $this->error(__('code为空'));
        }
        $appid = '';
        $app_secret = '';
        $site = Config::get('site');
        $appid = $site['min_appid'];;
        $app_secret = $site['min_appsecret'];;
        if($appid == ''|| $app_secret == ''){
            $this->error(__('appid或app_secret为空'));

        }
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$app_secret."&js_code=".$code."&grant_type=authorization_code";
         $data = doCurl($url);
         if(isset($data['openid'])){
             $ret =  $this->auth->wechatlogin($data['openid'],$nickname,$avatar,$pid,'miniapp');
             if ($ret) {
                $userinfo =  $this->auth->getUserinfo();
                $res = ['userinfo' =>$userinfo];
                $this->success(__('登陆成功'), $res);
            } else {
                $this->error($this->auth->getError());
            }
         }else{
             $data['code'] = 4000;
             $data['msg'] = '登录出错';
             $this->error($data);
         }
        $this->success($data);
    }

    public function user_info(){
        $userinfo = $this->auth->getUserinfo();

        $this->success('', ['userInfo' => $userinfo]);
    }

    public function get_game_child(){
        $Gamechild = new Gamechild();
        $list = $Gamechild->order('weigh asc')->select();
        foreach($list as $key=>$item){
            $list[$key]['game_image'] = cdnurl($item['image'],true);

        }

        $this->success('', $list);
    }


    public function create_game_room(){
        $Gameroom = new Gameroom();

        $pwd = $this->request->post('pwd','');

        if($pwd){
            $insert['pwd'] = md5(md5($pwd));
        }
        $insert['user_id'] = $this->auth->id;

        $this->success('', $list);
    }


    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="账号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取积分充值配置
     *
     * @ApiMethod (POST)
     */
    public function get_charge_config(){
        $config_list = \app\common\model\user\Jifenconfig::order('weigh asc')->select();
        $this->success(__('获取成功'), $config_list);
    }

    /**
     * 获取积分充值配置
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function charge(){
        $id = $this->request->post('id');
        $config_info = \app\common\model\user\Jifenconfig::where('id',$id)->find();

        $pay_money = $config_info['money'];
        $order_id = $this->get_order_id();
        $title = '学神之域积分充值';

        $insert_data['user_id'] = $this->auth->id;
        $insert_data['totalamount'] = $pay_money;
        $insert_data['order_sn'] = $order_id;

        $effect = \app\common\model\order\Orderlist::insert($insert_data);

        $params = [
            'amount'    => $pay_money,
            'orderid'   =>$order_id,
            'type'      =>"wechat",
            'title'     => $title,
            'method'    => 'miniapp',
            'openid'    => $this->auth->mini_openid,
        ];

        $response = \addons\epay\library\Service::submitOrder($params);

        $this->success(__('获取成功'), $response);
    }

    public function get_order_id(){
        //订单号主体
        $order_id_main = date('YmdHis') . rand(10000000,99999999);
        //订单号长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for($i=0; $i<$order_id_len; $i++){
            $order_id_sum += (int)(substr($order_id_main,$i,1));
         }
        //唯一订单号
        $order_sn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
        return $order_sn;
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="code", type="string", required=true, description="验证码")
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    //获取牌面信息
    public function create_(){

    }

    //获取牌面信息
    public function get_pai_init(){
        $pai_list = \app\common\model\game\Gamepai::select();

        $all_pai_array = [];
        foreach($pai_list as $key=>$item){
            for($i=0;$i<4;$i++){
                $all_pai_array[] = $item;
            }
        }

        $array_rand = array_rand($all_pai_array,13);
        $output_pai = [];

        for($i=0;$i<count($array_rand);$i++){
            $output_pai[$i]['image'] = cdnurl($all_pai_array[$i]['image'],true);
            $output_pai[$i]['select'] = false;
        }

        $this->success(__('获取成功'),$output_pai);
    }


    // 判断吃牌
    public function checkChi($handCards, $discardCard)
    {
        $type = floor($discardCard / 10);
        $value = $discardCard % 10;

        // 风牌和箭牌不能吃
        if ($type == 4 || $type == 5) {
            return false;
        }

        $possibleChi = [];

        // 检查是否能组成顺子
        for ($i = -2; $i <= 0; $i++) {
            $cards = [];
            $valid = true;

            for ($j = 0; $j < 3; $j++) {
                $checkCard = ($type * 10) + ($value + $i + $j);
                if ($checkCard < $type * 10 + 1 || $checkCard > $type * 10 + 9) {
                    $valid = false;
                    break;
                }

                if ($checkCard == $discardCard) {
                    $cards[] = $checkCard;
                    continue;
                }

                if (in_array($checkCard, $handCards)) {
                    $cards[] = $checkCard;
                } else {
                    $valid = false;
                    break;
                }
            }

            if ($valid && count($cards) == 2) {
                $possibleChi[] = $cards;
            }
        }

        return empty($possibleChi) ? false : $possibleChi;
    }

    // 判断碰牌
    public function checkPeng($handCards, $discardCard)
    {
        $count = 0;
        foreach ($handCards as $card) {
            if ($card == $discardCard) {
                $count++;
            }
        }

        return $count >= 2;
    }

    // 判断杠牌
    public function checkGang($handCards, $discardCard = null)
    {
        $gangCards = [];

        if ($discardCard) {
            // 明杠：别人打出的牌
            $count = 0;
            foreach ($handCards as $card) {
                if ($card == $discardCard) {
                    $count++;
                }
            }
            if ($count == 3) {
                $gangCards[] = $discardCard;
            }
        } else {
            // 暗杠：自己手牌
            $cardCount = array_count_values($handCards);
            foreach ($cardCount as $card => $count) {
                if ($count == 4) {
                    $gangCards[] = $card;
                }
            }
        }

        return empty($gangCards) ? false : $gangCards;
    }

    // 判断胡牌
    public function checkHu($handCards, $discardCard = null)
    {
        if ($discardCard) {
            $handCards[] = $discardCard;
        }

        sort($handCards);

        // 七对判断
        if ($this->isQiDui($handCards)) {
            return true;
        }

        // 普通胡牌判断
        return $this->isNormalHu($handCards);
    }

    // 七对判断
    private function isQiDui($cards)
    {
        if (count($cards) != 14) return false;

        $counts = array_count_values($cards);
        foreach ($counts as $count) {
            if ($count != 2 && $count != 4) {
                return false;
            }
        }

        // 检查四张牌的数量
        $fourCount = 0;
        foreach ($counts as $count) {
            if ($count == 4) $fourCount++;
        }

        return $fourCount <= 1;
    }

    // 普通胡牌判断
    private function isNormalHu($cards)
    {
        if (count($cards) != 14) return false;

        // 移除将牌后递归检查
        $counts = array_count_values($cards);

        // 找将牌
        foreach ($counts as $card => $count) {
            if ($count >= 2) {
                $tempCards = $cards;
                $this->removeCards($tempCards, $card, 2);

                if ($this->checkMeld($tempCards)) {
                    return true;
                }
            }
        }

        return false;
    }

    // 检查顺子和刻子
    private function checkMeld($cards)
    {
        if (empty($cards)) return true;

        sort($cards);
        $firstCard = $cards[0];

        // 检查刻子
        if (count($cards) >= 3 &&
            $cards[0] == $cards[1] &&
            $cards[0] == $cards[2]) {
            $tempCards = $cards;
            $this->removeCards($tempCards, $firstCard, 3);
            if ($this->checkMeld($tempCards)) {
                return true;
            }
        }

        // 检查顺子 (只针对万条筒)
        $type = floor($firstCard / 10);
        if ($type >= 1 && $type <= 3) {
            $card2 = $firstCard + 1;
            $card3 = $firstCard + 2;

            if (in_array($card2, $cards) && in_array($card3, $cards)) {
                $tempCards = $cards;
                $this->removeCards($tempCards, $firstCard, 1);
                $this->removeCards($tempCards, $card2, 1);
                $this->removeCards($tempCards, $card3, 1);

                if ($this->checkMeld($tempCards)) {
                    return true;
                }
            }
        }

        return false;
    }


    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="bio", type="string", required=true, description="个人简介")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $mobile = $this->request->post('mobile');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');

        $user->nickname = $nickname;
        $user->mobile = $mobile;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams (name="code", type="string", required=true, description="Code码")
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
}
